package com.zidian.teacher.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.zidian.teacher.R;
import com.zidian.teacher.bean.ListGroupBean;
import com.zidian.teacher.utils.ProgressBarBlackUtil;
import com.zidian.teacher.utils.ToastUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import com.zidian.teacher.adapter.EditGroupHasAdapter;
import com.zidian.teacher.bean.ListStudyBean;
import com.zidian.teacher.bean.PutGroupBean;
import com.zidian.teacher.common.Constant;
import com.zidian.teacher.common.ToolBarActivity;
import com.zidian.teacher.utils.GetUserInfo;

/**
 * Created by Administrator on 2016/9/7 0007.
 */
public class EditGroupActivity extends ToolBarActivity {
    @Bind(R.id.study_recycler)
    RecyclerView studyRecycler;
    @Bind(R.id.group_total_no)
    TextView groupTotalNo;
    @Bind(R.id.confirm_add)
    Button confirmAdd;
    @Bind(R.id.group_name_has)
    TextView groupNameHas;
    @Bind(R.id.group_total)
    TextView groupTotal;
    @Bind(R.id.study_recycler_has)
    RecyclerView studyRecyclerHas;
    @Bind(R.id.confirm_delete)
    Button confirmDelete;
    private TextView updataSure;
    private PutGroupBean putBean;
    private List<ListGroupBean> groupBeanList;
    private LinearLayoutManager mStudyLayoutManager;
    private LinearLayoutManager mHasStudyLayoutManager;
    private EditGroupHasAdapter noAdapter;
    private EditGroupHasAdapter hasAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setToolbarView(R.layout.toolbar_both);
        setContentView(R.layout.activity_edit_group);
        ButterKnife.bind(this);
        setTitle("编辑学生分组");
        updataSure = (TextView) findViewById(R.id.toolbar_sure);
        putBean = (PutGroupBean) getIntent().getSerializableExtra("groupBean");

        groupBeanList = putBean.getGroupBeans();
        initView();

    }

    private void initView() {
        noAdapter = new EditGroupHasAdapter(this, groupBeanList, 0);
        hasAdapter = new EditGroupHasAdapter(this, groupBeanList, 1);
        mStudyLayoutManager = new GridLayoutManager(this, 5);
        mHasStudyLayoutManager = new GridLayoutManager(this, 5);
        studyRecycler.setLayoutManager(mStudyLayoutManager);
        studyRecyclerHas.setLayoutManager(mHasStudyLayoutManager);
        studyRecycler.setAdapter(noAdapter);
        studyRecyclerHas.setAdapter(hasAdapter);
        groupTotalNo.setText(groupBeanList.get(groupBeanList.size() - 1).getGroupTotal());
        groupTotal.setText(groupBeanList.get(0).getGroupTotal());
        groupNameHas.setText(groupBeanList.get(0).getGroupName());


        noAdapter.setOnItemClickListener(new EditGroupHasAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                boolean isSelect = groupBeanList.get(groupBeanList.size() - 1).getStudyBeans().get(position).isSelect();
                groupBeanList.get(groupBeanList.size() - 1).getStudyBeans().get(position).setIsSelect(!isSelect);
                noAdapter.setGroupList(groupBeanList, 0);
                noAdapter.notifyDataSetChanged();
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });
        hasAdapter.setOnItemClickListener(new EditGroupHasAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                boolean isSelect = groupBeanList.get(0).getStudyBeans().get(position).isSelect();
                groupBeanList.get(0).getStudyBeans().get(position).setIsSelect(!isSelect);
                hasAdapter.setGroupList(groupBeanList, 1);
                hasAdapter.notifyDataSetChanged();
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });


        confirmAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                confrimBtn(true);

//                Log.e("Result", petToJson(groupBeanList.get(groupBeanList.size() - 1).getStudyBeans().get(0)));

            }
        });
        confirmDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                confrimBtn(false);
            }
        });

        updataSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updataStudent();
            }
        });

    }


    private void confrimBtn(boolean isAdd) {

        if (isAdd) {
            for (int i = 0; i < groupBeanList.get(groupBeanList.size() - 1).getStudyBeans().size(); i++) {
                if (groupBeanList.get(groupBeanList.size() - 1).getStudyBeans().get(i).isSelect()) {
                    groupBeanList.get(0).getStudyBeans().add(groupBeanList.get(groupBeanList.size() - 1).getStudyBeans().get(i));
                    groupBeanList.get(groupBeanList.size() - 1).getStudyBeans().remove(i);
                    i--;
                }
            }
        } else {
            for (int i = 0; i < groupBeanList.get(0).getStudyBeans().size(); i++) {
                if (groupBeanList.get(0).getStudyBeans().get(i).isSelect()) {
                    groupBeanList.get(groupBeanList.size() - 1).getStudyBeans().add(groupBeanList.get(0).getStudyBeans().get(i));
                    groupBeanList.get(0).getStudyBeans().remove(i);
                    i--;
                }
            }
        }
        noAdapter.setGroupList(groupBeanList, 0);
        hasAdapter.setGroupList(groupBeanList, 1);
        noAdapter.notifyDataSetChanged();
        hasAdapter.notifyDataSetChanged();
    }

    public String petToJson(ListStudyBean pet) {
        String jsonresult = "";//定义返回字符串
        JSONObject object = new JSONObject();//创建一个总的对象，这个对象对整个json串
        try {
            JSONArray jsonarray = new JSONArray();//json数组，里面包含的内容为pet的所有对象
            JSONObject jsonObj = new JSONObject();//pet对象，json形式
            jsonObj.put("studentId", pet.getStudyID());//向pet对象里面添加值
            jsonObj.put("studyName", pet.getStudyName());
            // 把每个数据当作一对象添加到数组里
            jsonarray.put(jsonObj);//向json数组里面添加pet对象
            object.put("pet", jsonarray);//向总对象里面添加包含pet的数组
            jsonresult = object.toString();//生成返回字符串
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return jsonresult;
    }

    private void updataStudent() {

        String student = "";
        try {
            JSONArray jsonarray = new JSONArray();
            for (int i = 0; i < groupBeanList.size(); i++) {
                for (int j = 0; j < groupBeanList.get(i).getStudyBeans().size(); j++) {
                    JSONObject jsonObjAnswer = new JSONObject();//pet对象，json形式

                    jsonObjAnswer.put("groupId", groupBeanList.get(i).getStudyBeans().get(j).getGroupId());
                    jsonObjAnswer.put("groupingId", groupBeanList.get(i).getGroupingId());
                    jsonarray.put(jsonObjAnswer);
                }
            }
            student = jsonarray.toString();//生成返回字符串
        } catch (JSONException e) {
            e.printStackTrace();
        }

        String loginUrl = Constant.URL_GOAL + "grouping/updStu";
        HashMap<String, String> map = new HashMap<>();
        map.put("student", student);
        map.put("teacherId", GetUserInfo.getTeacherId(context));
        map.put("token", GetUserInfo.getToken(context));

        ProgressBarBlackUtil.loadShow(this);
        OkHttpUtils.post().url(loginUrl).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ProgressBarBlackUtil.loadCancel();
                ToastUtil.showToast(context, "获取列表失败！");
            }

            @Override
            public void onResponse(String response, int id) {
                ProgressBarBlackUtil.loadCancel();
                Log.e("T", response);
                try {
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(response);
                    int resultCode = jsonObject.getInt("code");

                    if (resultCode != 200) {
                        ToastUtil.showToast(context, jsonObject.getString("message"));
                        return;
                    } else {
                        ToastUtil.showToast(context, "编辑成功");
                        Intent intent = new Intent();
                        intent.putExtra("hasChange", true);
                        setResult(6001, intent);
                        finish();
                        return;
                    }

                } catch (JSONException e) {

                }
            }
        });
    }


}
